package com.zweirm.lagee_quizing_web.service;

import com.zweirm.lagee_quizing_web.domain.Quiz;
import com.zweirm.lagee_quizing_web.domain.Result;
import com.zweirm.lagee_quizing_web.domain.StudentUser;
import com.zweirm.lagee_quizing_web.repository.QuizRepository;
import com.zweirm.lagee_quizing_web.repository.ResultRepository;
import com.zweirm.lagee_quizing_web.repository.StudentUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

@Service
public class ResultService {
    @Autowired
    private StudentUserRepository studentUserRepository;

    @Autowired
    private QuizRepository quizRepository;

    @Autowired
    private ResultRepository resultRepository;

    public Result findResultByUserIdAndQuiz(Long quizId) {
        // 获取当前用户
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String email = userDetails.getUsername();
        StudentUser studentUser = studentUserRepository.findStudentUserByEmail(email);

        // 获取当前考试
        Quiz quiz = quizRepository.findQuizById(quizId);

        // 获取考试成绩
        return resultRepository.findResultByStudentUserAndQuiz(studentUser, quiz);
    }

    public void saveResult(String passRate, Quiz quiz) {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String email = userDetails.getUsername();
        StudentUser studentUser = studentUserRepository.findStudentUserByEmail(email);

        Result result = new Result();

        result.setPassRate(passRate);
        result.setQuiz(quiz);
        result.setStudentUser(studentUser);
        resultRepository.save(result);
    }
}
